﻿using MarchingSquares;
using UnityEngine;
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
using UnityEngine.InputSystem;
#endif

namespace Procedural.Marching.Squares.Utils
{
    public class NoiseOffsetMover : MonoBehaviour
    {
        [Header("Settings parameters")] public float scrollSpeed = 1.0f;
        public bool timeScroll = false;

        // Scrolling voxel map
        private VoxelMap map;

        // Get the input direction
        private Vector2 inputDirection;

        // Used by the condition time scroll
        private float time;
        private Vector2 timeDirection;

#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER

        [SerializeField] private InputAction _directionInput;
#endif
        private void Start()
        {
            enabled = false;
        }

        private void OnEnable()
        {
            map = FindObjectOfType<VoxelMap>();
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
            _directionInput.Enable();
#endif
        }

        private void Update()
        {
            if (timeScroll)
            {
                time = Time.deltaTime;
                timeDirection = Vector2.one * time;
            }
            else
            {
                time = 0f;
                timeDirection = Vector2.zero;
            }
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
            inputDirection = _directionInput.ReadValue<Vector2>() * Time.deltaTime;
#else
            inputDirection = (Vector2.right * Input.GetAxis("Horizontal") + Vector2.up * Input.GetAxis("Vertical")) *
                             Time.deltaTime;
#endif
            inputDirection.Normalize();
            // Don't scroll if any direction is 0
            if (inputDirection.sqrMagnitude != 0 || timeDirection.sqrMagnitude != 0)
            {
                map.AddNoiseOffset(inputDirection * scrollSpeed + timeDirection * scrollSpeed);
            }
            for (int i = 0; i < map.chunks.Count; i++)
            {
                map.SetChunkVoxelNoise(i);
            }
        }
    }
}